package com.fanrenqiji.modules.sys.service.impl;

import com.fanrenqiji.common.utils.StringUtils;
import com.fanrenqiji.common.utils.SystemAuthorizingCacheUtils;
import com.fanrenqiji.modules.sys.dao.AreaDao;
import com.fanrenqiji.modules.sys.entity.Area;
import com.fanrenqiji.modules.sys.service.AreaService;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月11日 下午2:06:34
 * @description
 */
@Service
@Transactional(readOnly = true)
public class AreaServiceImpl implements AreaService {

	@Autowired
	private AreaDao areaDao;

	@Override
	public Area findById(Long id) {
		return areaDao.findOne(id);
	}

	@Override
	public List<Area> findAll() {
		return UserUtils.getAreaList();
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Area area) {
		area.setParent(this.findById(area.getParent().getId()));
		String oldParentIds = area.getParentIds(); // 获取修改前的parentIds，用于更新子节点的parentIds
		area.setParentIds(area.getParent().getParentIds()
				+ area.getParent().getId() + ",");
		areaDao.clear();
		areaDao.save(area);
		// 更新子节点 parentIds
		List<Area> list = areaDao.findByParentIdsLike("%," + area.getId() + ",%");
		for (Area e : list) {
			e.setParentIds(e.getParentIds().replace(oldParentIds,
					area.getParentIds()));
		}
		areaDao.save(list);
		SystemAuthorizingCacheUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(Long id) {
		areaDao.deleteById(id, "%," + id + ",%");
		SystemAuthorizingCacheUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}

	@Override
	public List<String> findAreaByCode(String code) {
		return areaDao.findAreaByCode(code);
		
	}
	
	/**
	 * type 区域类型 2省份 3：市 parentId 父节点ID
	 */
	@Override
	public List<Area> getAreaListByTypeAndParentId(String type, String parentId) {
		DetachedCriteria dc = areaDao.createDetachedCriteria();
		
		if(StringUtils.isNotEmpty(type)){
			dc.add(Restrictions.eq("type", type));
		}
		if (StringUtils.isNotEmpty(parentId)) {
			dc.add(Restrictions.eq("parent.id", new Long(parentId)));
		}
		dc.add(Restrictions.eq(Area.DEL_FLAG, Area.DEL_FLAG_NORMAL));
		// 根据 type sort 和id排序
		dc.addOrder(Order.asc("code"));
		List areas =null;
		try {
			 areas = areaDao.find(dc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return areas;

	}
	
	
	/**
	 * type 区域类型 2省份 3：市 parentId 父节点ID
	 */
	@Override
	public List<Area> findAreaByParentId(String parentId) {
		return areaDao.findAreaByParentId(new Long(parentId));

	}
	
	
	

}
